// app/controller/users.js
const Controller = require('./baseController')
const { Op } = require('sequelize')

class RoleController extends Controller {
	// 获取所有的列表不分页
	async listAll() {
		const { ctx } = this
		const data = await ctx.service.role.listAll()
		console.log(data)
		ctx.helper.success({ data })
	}
	// 获取所欲的角色列表 分页
	async list() {
		const { ctx } = this
		const {
			query: { pageSize = 8, currentPage = 1 },
			helper,
		} = ctx
		let queryArr = {
			limit: helper.toInt(pageSize),
			offset: (helper.toInt(currentPage) - 1) * helper.toInt(pageSize),
		}
		const data = await ctx.service.role.list(queryArr)
		helper.success({ data })
	}
	// 根据角色名称模糊查询
	async findLike() {
		const { ctx } = this
		const {
			query: { status, begin, end, pageSize = 8, currentPage = 1 },
			helper,
		} = ctx

		let where = {}
		if (status) {
			where['status'] = {
				[Op.eq]: ctx.query.status ? JSON.parse(ctx.query.status) : true,
			}
		}
		if (begin && end) {
			where['createdAt'] = {
				[Op.between]: [ctx.query.begin, ctx.query.end],
			}
		}

		let options = {
			limit: helper.toInt(pageSize),
			offset: (helper.toInt(currentPage) - 1) * helper.toInt(pageSize),
			where: {
				name: {
					[Op.substring]: ctx.query.name ?? '',
				},
				remark: {
					[Op.substring]: ctx.query.remark ?? '',
				},
				...where,
			},
		}
		const data = await ctx.service.role.findLike(options)
		helper.success({ data })
	}
	// 添加角色
	async add() {
		const { ctx } = this
		const { name, remark } = ctx.request.body
		const { helper } = ctx
		if (!name || !name.trim()) {
			return helper.fail({ msg: '角色描述不能够为空！' })
		}
		if (!remark || !remark.trim()) {
			return helper.fail({ msg: '角色标识不能够为空！' })
		}
		let options = {
			where: {
				name,
			},
		}
		const res = await ctx.service.role.add(ctx.request.body, options)
		if (res.flag) {
			helper.success({ data: res.data.dataValues, msg: '添加成功' })
		} else {
			helper.fail({ msg: res.msg })
		}
	}

	// 删除角色
	async del() {
		const { ctx } = this
		let { ids } = ctx.request.body
		const { helper } = ctx
		const res = await ctx.service.role.del(ids)
		if (res.flag) {
			helper.success({ msg: '删除成功' })
		} else {
			helper.fail({ msg: res.msg })
		}
	}
	// 修改角色

	async update() {
		const { ctx } = this
		let {
			request: { body },
			helper,
		} = ctx
		if (!body.id) return helper.fail({ msg: '角色id必填字段！' })

		const odl = await ctx.model.Role.findByPk(ctx.request.body.id)

		if (!odl) {
			return helper.fail({ msg: '角色不存在！' })
		}
		const res = await ctx.service.role.update(ctx.request.body)
		if (res[0]) {
			helper.success({ msg: '角色修改成功！' })
		} else {
			helper.fail({ msg: '角色修改失败！' })
		}
	}
	// 批量更新
	async updateList() {
		const { ctx } = this
		const res = await ctx.service.role.updateList(ctx.request.body.roles)
		if (res.flag && res.count) {
			ctx.helper.success({
				msg: '批量添加成功！',
				inserCount: res.count,
			})
		} else {
			ctx.helper.fail({ msg: '批量添加失败！数据重复！' })
		}
	}
}
module.exports = RoleController
